package br.com.carlosbarbero.springbatch.databasetoxml.writer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.batch.core.StepExecution;
import org.springframework.batch.core.annotation.AfterStep;
import org.springframework.batch.core.annotation.AfterWrite;
import org.springframework.batch.core.annotation.BeforeStep;
import org.springframework.batch.core.annotation.BeforeWrite;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import br.com.carlosbarbero.springbatch.databasetoxml.bean.DadosEmpresaSaudeOdonto;
import br.com.carlosbarbero.springbatch.databasetoxml.bean.HeaderEmpresaSaude;

@Scope("step")
@Component("empresaSaudeWriter")
public class EmpresaSaudeWriter implements ItemWriter<DadosEmpresaSaudeOdonto> {

	private Log logger = LogFactory.getLog(EmpresaSaudeWriter.class);

	private static final HeaderEmpresaSaude[] HEADERS = HeaderEmpresaSaude
			.values();

	@Autowired
	@Qualifier("caminhoArquivoTemp")
	private Properties caminhoArquivoTemp;

	private File createTempFile = null;
	private String outputFilename;
	private Workbook workbook;
	private CellStyle dataCellStyle;
	private int currRow = 0;
	private Row row;

	private void addHeaders(Sheet sheet) {

		Workbook wb = sheet.getWorkbook();

		CellStyle style = wb.createCellStyle();
		Font font = wb.createFont();

		font.setFontHeightInPoints((short) 10);
		font.setFontName("Arial");
		font.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setFont(font);

		Row row = sheet.createRow(2);
		int col = 0;

		for (HeaderEmpresaSaude header : HEADERS) {
			Cell cell = row.createCell(col);
			cell.setCellValue(header.toString());
			cell.setCellStyle(style);
			col++;
		}
		currRow++;
	}

	private void addTitleToSheet(Sheet sheet) {

		Workbook wb = sheet.getWorkbook();

		CellStyle style = wb.createCellStyle();
		Font font = wb.createFont();

		font.setFontHeightInPoints((short) 14);
		font.setFontName("Arial");
		font.setBoldweight(Font.BOLDWEIGHT_BOLD);
		style.setAlignment(CellStyle.ALIGN_CENTER);
		style.setFont(font);

		Row row = sheet.createRow(currRow);
		row.setHeightInPoints(16);

		

		Cell cell = row.createCell(0, Cell.CELL_TYPE_STRING);
		cell.setCellValue("Lista de Empresas Sistema Central");
		cell.setCellStyle(style);

		CellRangeAddress range = new CellRangeAddress(0, 0, 0, 7);
		sheet.addMergedRegion(range);
		currRow++;

	}

	private void initDataStyle() {
		dataCellStyle = workbook.createCellStyle();
		Font font = workbook.createFont();

		font.setFontHeightInPoints((short) 10);
		font.setFontName("Arial");
		dataCellStyle.setAlignment(CellStyle.ALIGN_LEFT);
		dataCellStyle.setFont(font);
	}

	private void createStringCell(Row row, String val, int col) {
		Cell cell = row.createCell(col);
		cell.setCellType(Cell.CELL_TYPE_STRING);
		cell.setCellValue(val);
	}

	private void createNumericCell(Row row, Integer val, int col) {
		Cell cell = row.createCell(col);
		cell.setCellType(Cell.CELL_TYPE_NUMERIC);
		cell.setCellValue(val);
	}

	public void write(List<? extends DadosEmpresaSaudeOdonto> paramList)
			throws Exception {

		for (DadosEmpresaSaudeOdonto dadosEmpresaSaude : paramList) {

			Sheet sheet = workbook.getSheetAt(0);
			int ultimaLinha = sheet.getLastRowNum();

			Row row = sheet.createRow(ultimaLinha + 1);
			createNumericCell(row, dadosEmpresaSaude.getGrupoEmpresa(), 0);
			createStringCell(row, dadosEmpresaSaude.getCodEmpresa(), 1);
			createStringCell(row, dadosEmpresaSaude.getNomeFantasia(), 2);
			createNumericCell(row, dadosEmpresaSaude.getNumeroContrato(), 3);
			createNumericCell(row, dadosEmpresaSaude.getNumeroApolice(), 4);
			createStringCell(row, dadosEmpresaSaude.getDataIncio(), 5);
			createStringCell(row, dadosEmpresaSaude.getDataFim(), 6);
			createNumericCell(row, dadosEmpresaSaude.getCodProd(), 7);
			createNumericCell(row, dadosEmpresaSaude.getCodEstruturaVenda(), 8);
			createStringCell(row, dadosEmpresaSaude.getDataInclusao(), 9);
			createStringCell(row, dadosEmpresaSaude.getDataInstalacao(), 10);
			createStringCell(row, dadosEmpresaSaude.getTipoSistema(), 11);
			createStringCell(row, dadosEmpresaSaude.getTipoProduto(), 12);
			createStringCell(row, dadosEmpresaSaude.getTipoGrupo(), 13);
			createNumericCell(row, dadosEmpresaSaude.getQuantidadeVidas(), 14);
			createStringCell(row, dadosEmpresaSaude.getNomeSucursal(), 15);
			createStringCell(row, dadosEmpresaSaude.getSigUf(), 16);
			createStringCell(row, dadosEmpresaSaude.getEmailGrupo(), 17);
			createNumericCell(row,
					dadosEmpresaSaude.getQuantidadeMovimentacao(), 18);

		}

	}

	// Para cada interacao

	// Para cada Step

	@BeforeStep
	public void beforeStep(StepExecution stepExecution) {

		if (createTempFile == null) {
			try {
				createTempFile = File.createTempFile("tempxls", ".xlsx");
			} catch (IOException e) {
				logger.error("Erro na criacao do arquivo", e);
			}
		}

		workbook = new SXSSFWorkbook(100);
		Sheet sheet = workbook.createSheet("Empresa");
		sheet.createFreezePane(0, 3, 0, 3);
		sheet.setDefaultColumnWidth(20);

		addTitleToSheet(sheet);
		currRow++;
		addHeaders(sheet);
		initDataStyle();

	}

	@AfterStep
	public void afterStep(StepExecution stepExecution) throws IOException {

		FileOutputStream stream = new FileOutputStream(createTempFile);
		workbook.write(stream);
		stream.flush();
		stream.close();

		caminhoArquivoTemp.put("file.path", createTempFile.getAbsolutePath());

	}

}
